package com._520it.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class DruidUtil {
	
private static Properties p=new Properties();
	
	private static DataSource dataSource=null;
	
	static{
		//当静态代码块所在类的字节码（jdbc.class）被加载进JVM，就执行
		try {
			ClassLoader loader=Thread.currentThread().getContextClassLoader();
			InputStream is=loader.getResourceAsStream("dbcp.properties");
			p.load(is);
			// 创建DataSource对象
			dataSource=DruidDataSourceFactory.createDataSource(p);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//创建并返回连接对象
	
	public static Connection getConn(){
		try {
			return dataSource.getConnection();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		throw new RuntimeException("数据库连接错误");
		
	}
	
	/*
	 * 关闭资源
	 */
	public static void close(Connection conn,Statement st,ResultSet rs){
		try {
			if (rs != null) {
				rs.close();
			}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						try {
							if (st != null) {
								st.close();
							}
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							try {
								if (conn != null) {
									conn.close();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
	}
}
